<template>
    <custom-page-box>
        <div class="container">
            <div class="header" v-if="disabledKey">
                <a-button
                    type="primary"
                    @click="
                        () => {
                            $router.go(-1)
                        }
                    "
                >
                    返回
                </a-button>
            </div>
            <a-form-model
                ref="ruleForm"
                :model="form"
                :rules="rules"
                :label-col="{ span: 2 }"
                :wrapper-col="{ span: 7 }"
            >
                <a-form-model-item label="优品标题" prop="title">
                    <a-input v-model="form.title" :maxLength="30" :disabled="disabledKey" />
                    <span class="len">{{ form.title.length }}/30</span>
                </a-form-model-item>
                <a-form-model-item label="分类" prop="kindId">
                    <a-cascader
                        :field-names="{ label: 'name', value: 'id', children: 'children' }"
                        :options="optionsList"
                        placeholder="请选择分类"
                        v-model="form.kindId"
                        :disabled="disabledKey"
                    />
                </a-form-model-item>
                <a-form-model-item label="标签" prop="label">
                    <AddLbael
                        v-if="!disabledKey"
                        v-model="form.label"
                        placeholder="请输入标签"
                        :max="5"
                        :minLabel="2"
                        :maxLength="6"
                        isIcon="plus"
                        :isShow="true"
                        tipText="至少2个字，最多6个字，最多5个标签"
                    />
                    <span v-else>{{ labelTitle }}</span>
                </a-form-model-item>
                <a-form-model-item label="省市区镇" prop="cityCode">
                    <city-cascader
                        :disabled="disabledKey"
                        placeholder="请选择省市区镇"
                        v-model="form.cityCode"
                    ></city-cascader>
                </a-form-model-item>
                <a-form-model-item label="定位" prop="address" class="address">
                    <a-input
                        :disabled="disabledKey"
                        readOnly
                        placeholder="请选择详细位置"
                        v-model="form.address"
                        @click="show = true"
                    >
                        <a-icon slot="suffix" type="environment" style="color: #1ba655" />
                    </a-input>
                </a-form-model-item>
                <a-form-model-item label="联系方式" prop="telephone">
                    <a-input :disabled="disabledKey" v-model="form.telephone" placeholder="请输入联系方式" />
                </a-form-model-item>
                <a-form-model-item label="供应商">
                    <a-input
                        :disabled="disabledKey"
                        v-model="form.supplier"
                        placeholder="请输入供应商"
                        :maxLength="20"
                    />
                    <span class="len">{{ form.supplier.length }}/20</span>
                </a-form-model-item>
                <a-form-model-item label="图片" prop="imgUrl" class="img-box">
                    <p slot="extra" class="tips" v-if="!disabledKey">
                        支持上传jpe、jpeg、png <br />仅支持上传9张，每张不超过6M，尺寸为400*262
                    </p>
                    <custom-cropper-image
                        :width="400"
                        :height="262"
                        path="/fine-product/img/"
                        v-model="form.imgUrl"
                        :max="9"
                        :fileSize="6"
                        keys="优品图片"
                        :edit="!disabledKey"
                    ></custom-cropper-image>
                </a-form-model-item>
                <a-form-model-item label="视频">
                    <p v-if="!disabledKey" slot="extra" class="tips">仅支持上传一段视频，视频大小不超过50M</p>
                    <custom-video-upload
                        :edit="!disabledKey"
                        v-model="form.videoList"
                        path="/fine-product/video/"
                    ></custom-video-upload>
                </a-form-model-item>
                <a-form-model-item label="简介" prop="description" class="desc-box">
                    <a-input :disabled="disabledKey" type="textarea" v-model="form.description" :maxLength="100" />
                    <span class="len">{{ form.description.length }}/100</span>
                </a-form-model-item>
                <a-form-model-item label="优品详情" prop="detail" class="rich-box">
                    <tinymce-editor
                        v-model="form.detail"
                        cosPath="fine-product-richText"
                        :height="400"
                        :disabled="disabledKey"
                    ></tinymce-editor>
                </a-form-model-item>
                <a-form-model-item :wrapper-col="{ span: 14, offset: 2 }" v-if="!disabledKey">
                    <a-button
                        @click="
                            () => {
                                $router.go(-1)
                            }
                        "
                        class="btn"
                    >
                        取消
                    </a-button>
                    <a-button style="margin-left: 20px" type="primary" @click="onSubmit(0)"> 保存 </a-button>
                    <a-button style="margin-left: 20px" type="primary" @click="onSubmit(1)"> 保存并发布 </a-button>
                </a-form-model-item>
            </a-form-model>
        </div>
        <mapLocation :isShow="show" @Mapok="handleChange" @hide="show = false" :cityInfo="cityInfo" />
    </custom-page-box>
</template>
<script>
import AddLbael from '@/components/add-label'
import cityCascader from '@/components/city-cascader'
import mapLocation from '@/components/map-location/index.vue'
import TinymceEditor from '@/components/tinymce-editor/index.vue'
const validTel = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入联系方式'))
    }
    if (isNaN(Number(value))) {
        callback(new Error('请输入正确的联系方式'))
    } else {
        callback()
    }
}

export default {
    components: {
        AddLbael,
        cityCascader,
        mapLocation,
        TinymceEditor
    },
    data () {
        return {
            optionsList: [],
            form: {
                title: '',
                kindId: [],
                label: [],
                cityCode: '',
                telephone: '',
                address: '',
                latitude: '',
                longitude: '',
                province: '',
                city: '',
                area: '',
                supplier: '',
                imgUrl: [],
                videoList: {
                    videoUrl: '',
                    imgCoverUrl: ''
                },
                description: '',
                detail: ''
            },
            rules: {
                title: [{ required: true, message: '请填写优品标题', trigger: 'change' }],
                kindId: [{ required: true, message: '请选择分类', trigger: 'change' }],
                cityCode: [
                    {
                        required: true,
                        message: '请选择省市区镇',
                        trigger: 'change'
                    }
                ],
                address: [{ required: true, message: '请现在详细位置', trigger: 'change' }],
                telephone: [{ required: true, validator: validTel, trigger: 'change' }],
                imgUrl: [{ required: true, message: '请上传图片', trigger: 'change' }],
                description: [{ required: true, message: '请输入优品的简介', trigger: 'change' }],
                detail: [{ required: true, message: '请输入优品的详细内容', trigger: 'change' }]
            },
            show: false,
            itemId: ''
        }
    },
    computed: {
        cityInfo () {
            const { address, latitude, longitude, province, city, area } = this.form
            return { address, latitude, longitude, province, city, area }
        },
        disabledKey () {
            if (this.$route.query.edit === 'false') {
                return true
            } else {
                return false
            }
        },
        labelTitle () {
            return this.form.label.length ? this.form.label.map(item => item.name).join(',') : ''
        }
    },
    mounted () {
        this.getTypeTree()
        if (this.$route.query.id) {
            this.getDetails()
        }
    },
    methods: {
        // 查询详情
        async getDetails () {
            const res = await this.$ApiServer['fineproduct/detail']({
                id: this.$route.query.id
            })
            if (res.code === 200) {
                const {
                    title,
                    kindId,
                    cityCode,
                    label,
                    telephone,
                    address,
                    latitude,
                    longitude,
                    province,
                    city,
                    area,
                    supplier,
                    imgUrl,
                    videoUrl,
                    imgCoverUrl,
                    description,
                    detail,
                    id
                } = res.data
                this.itemId = id
                this.form = {
                    title: title || '',
                    kindId: kindId ? (kindId.length ? kindId.split(',') : []) : [],
                    label: label
                        ? label.length
                            ? res.data.label.split(',').map((item) => {
                                return {
                                    name: item
                                }
                            })
                            : []
                        : [],
                    cityCode: cityCode || '',
                    telephone: telephone || '',
                    address: address || '',
                    latitude: latitude || '',
                    longitude: longitude || '',
                    province: province || '',
                    city: city || '',
                    area: area || '',
                    supplier: supplier || '',
                    imgUrl: imgUrl ? (imgUrl.length ? imgUrl.split(',') : []) : [],
                    videoList: {
                        videoUrl: videoUrl || '',
                        imgCoverUrl: imgCoverUrl || ''
                    },
                    description: description || '',
                    detail: detail || ''
                }
            }
        },
        // 获取优品分类
        async getTypeTree () {
            const res = await this.$ApiServer['fineproduct/type']()
            if (res.code === 200) {
                res.data = res.data.filter(item => item.status !== 0 && item.children && item.children.length)
                res.data.forEach((item) => {
                    item.children = item.children.filter(subItem => subItem.status !== 0)
                })
                this.optionsList = res.data
            }
        },
        handleChange (data) {
            this.form.address = data.address
            this.form.latitude = data.latitude
            this.form.longitude = data.longitude
            this.form.province = data.province
            this.form.city = data.city
            this.form.area = data.area
            this.show = false
        },
        onSubmit (num) {
            console.log(num)
            if (num === 0) {
                if (this.form.kindId.length) {
                    this.subMitForm(num)
                } else {
                    this.$message.error('必须选择分类，才能保存')
                }
            } else {
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        this.subMitForm(num)
                    } else {
                        return false
                    }
                })
            }
        },
        resetForm () {
            this.$refs.ruleForm.resetFields()
        },

        async subMitForm (num) {
            const {
                cityCode,
                detail,
                imgUrl,
                kindId,
                label,
                address,
                latitude,
                longitude,
                province,
                city,
                area,
                supplier,
                telephone,
                title,
                description
            } = this.form
            const { videoUrl, imgCoverUrl } = this.form.videoList
            const res = await this.$ApiServer['fineproduct/submit']({
                cityCode: cityCode || null,
                detail: detail || null,
                imgUrl: imgUrl.length ? imgUrl.join(',') : null,
                kindId: kindId.length ? kindId.join(',') : null,
                label: label.length ? label.map(item => item.name).join(',') : null,
                address: address || null,
                latitude: latitude || null,
                longitude: longitude || null,
                province: province || null,
                city: city || null,
                area: area || null,
                supplier: supplier || null,
                telephone: telephone || null,
                title: title || null,
                videoUrl: videoUrl || null,
                imgCoverUrl: imgCoverUrl || null,
                description: description || null,
                status: num,
                id: this.itemId || null
            })
            if (res.code === 200) {
                this.$message.success('操作成功')
                this.$router.push('/fine-product')
            } else {
                this.$message.error(res.message)
            }
        }
    }
}
</script>

<style lang="less" scoped>
.container {
    background-color: #fff;
    overflow-y: auto;
    border-radius: 6px;
    height: 100%;
    padding: 0 20px;
}
.header {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    padding-top: 10px;
}

.ant-form {
    padding-top: 16px;
    ::v-deep {
        .ant-form-item {
            .ant-form-item-children {
                position: relative;
            }
            .tips {
                font-size: 0.12rem;
                color: #666666;
            }
            .len {
                position: absolute;
                right: 6px;
                bottom: -8px;
                height: 32px;
                font-size: 12px;
            }
            .btn {
                color: #1ba655;
                border-color: #1ba655;
            }
            &.rich-box,
            &.img-box {
                .ant-form-item-control-wrapper {
                    width: 800px !important;
                }
            }
            &.desc-box {
                .ant-form-item-control-wrapper {
                    textarea {
                        resize: none;
                        height: 120px;
                    }
                }
            }
            &.address {
                input {
                    cursor: pointer;
                    &.ant-input-disabled {
                        cursor: not-allowed;
                    }
                }
            }
        }
    }
}
</style>
